import { Button, message, Modal, Upload } from 'antd';
import React, { useState } from 'react';
import { UploadOutlined } from '@ant-design/icons';
import { baseURL } from 'utils/request';
import { getToken } from 'utils/strorage';

/*
  学习目标：限制上传图片最大数量为3
*/

const allowFileType = ['image/jpeg', 'image/jpg', 'image/png'];
export default function Test() {
  const [imgUrl, setImgUrl] = useState('');
  const [fileList, setFileList] = useState([]);

  const props = {
    // accept自定义弹出的上传窗口，显示哪些文件类型
    accept: ['.jpeg,.jpg,.png'],
    name: 'image',
    action: baseURL + '/v1_0/upload',
    headers: {
      authorization: `Bearer ${getToken()}`,
    },
    onChange(info) {
      console.log('info  ----->  ', info.fileList);
      setFileList(info.fileList);

      if (info.file.status === 'done') {
        message.success(`${info.file.name} 上传成功`);
      } else if (info.file.status === 'error') {
        message.error(`${info.file.name} 上传失败`);
      }
    },

    onPreview: (file) => {
      setImgUrl(file.thumbUrl);
    },

    beforeUpload: (file) => {
      if (!allowFileType.includes(file.type)) {
        message.warning('不允许上传的文件类型');

        return Upload.LIST_IGNORE;

        // 返回false可以阻止上传，会把不允许上传的图片，显示在前端界面上
        // return false;
      }
    },
  };

  return (
    <div>
      <Upload {...props} listType="picture-card" fileList={fileList}>
        {/* 当已上传的图片数量<3时，显示上传按钮，大于=3时，不显示按钮 */}
        {fileList.length < 3 && <Button icon={<UploadOutlined />} />}

        <Modal
          visible={!!imgUrl}
          footer={null}
          style={{ width: 470 }}
          onCancel={() => setImgUrl('')}
        >
          <img src={imgUrl} alt="" />
        </Modal>
      </Upload>
    </div>
  );
}
